﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FastReport;
using FastReport.Utils;
using System.IO;

namespace Print
{
    public partial class FormDesign : Form
    {
        public FormDesign()
        {
            InitializeComponent();
        }
        InitFile init = new InitFile();
        MsSqlHelper mssql = new MsSqlHelper();

        private void FormDesign_Load(object sender, EventArgs e)
        {
            //加载工作区
            Report report = new Report();
            designerControl1.Report = report;
            designerControl1.RefreshLayout();

            //report.RegisterData(GetDs());


            //更改设计器的选择文件对话框和打开报表对话框

            Config.DesignerSettings.CustomOpenDialog += new FastReport.Design.OpenSaveDialogEventHandler(DesignerSettings_CustomOpenDialog);
            Config.DesignerSettings.CustomOpenReport += new FastReport.Design.OpenSaveReportEventHandler(DesignerSettings_CustomOpenReport);

            //更改设计器的保存文件对话框和保存报表对话框
            Config.DesignerSettings.CustomSaveDialog += new FastReport.Design.OpenSaveDialogEventHandler(DesignerSettings_CustomSaveDialog);
            Config.DesignerSettings.CustomSaveReport += new FastReport.Design.OpenSaveReportEventHandler(DesignerSettings_CustomSaveReport);

            //得到当前模板信息
            GetRptTemplate();
        }

        //设置数据集
        private DataSet ds;
        private DataTable ReportTable
        {
            get
            {
                return ds.Tables[0];
            }
        }


        void DesignerSettings_CustomOpenDialog(object sender, FastReport.Design.OpenSaveDialogEventArgs e)
        {
            using (OpenForm openForm = new OpenForm())
            {
                //加载模板名
                openForm.ReportTable = ReportTable;
                //显示窗体
                DialogResult dr = openForm.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    //获取打开窗体选择的模板名
                    e.FileName = openForm.SelectedReportName;
                }
            }
        }

        void DesignerSettings_CustomOpenReport(object sender, FastReport.Design.OpenSaveReportEventArgs e)
        {
            //打开模板
            OpenReportTemplate(e.Report, e.FileName);
        }

        void DesignerSettings_CustomSaveDialog(object sender, FastReport.Design.OpenSaveDialogEventArgs e)
        {
            using (SaveForm saveForm = new SaveForm())
            {
                //显示窗体
                DialogResult dr = saveForm.ShowDialog();
                //取得SaveForm保存的模板名
                e.FileName = saveForm.ReportName;
            }
        }

        void DesignerSettings_CustomSaveReport(object sender, FastReport.Design.OpenSaveReportEventArgs e)
        {
            //保存模板
            SaveReportTemplate(e.Report, e.FileName);
        }

        //读取报表模板信息
        private void GetRptTemplate()
        {
            ds = new DataSet();
            ds.ReadXml(Application.StartupPath + "\\database.xml");
        }

        //写入报表模板信息
        private void WriteRptTemplate()
        {
            ds.WriteXml(Application.StartupPath + "\\database.xml",XmlWriteMode.WriteSchema);
        }

        //打开报表模板
        private void OpenReportTemplate(Report report,
        string reportName)
        {
            foreach (DataRow dr in ReportTable.Rows)
            {
                if (dr["ReportName"].ToString() == reportName)
                {
                    report.RegisterData(GetDs(dr["ReportSql"].ToString()));
                    //GetDs(dr["ReportSql"].ToString());
                    //读取模板信息，注意读取的是ReportStream，而不是ReportName
                    byte[] reportBytes = (byte[])dr["ReportStream"];
                    using (MemoryStream stream = new MemoryStream(reportBytes))
                    {
                        //加载报表
                        report.Load(stream);
                    }
                    return;
                }
            }
        }

        //保存报表模板
        private void SaveReportTemplate(Report report, string reportName)
        {
            //bool flag = false;
            
            //如果现在有同名模板，则提示需要更换保存的模板名字
            /*
            foreach (DataRow dr in ReportTable.Rows)
            {
                if (dr["ReportName"].ToString() == reportName)
                {              
                   // MessageBox.Show("现在有同名模板，请更换保存模板名后重试！", "系统提示！", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //return;
                }
            }
             */
            for (int i = 0; i < ReportTable.Rows.Count; i++)
            {
                if (ReportTable.Rows[i]["ReportName"].ToString() == reportName)
                {
                    ReportTable.Rows[i].Delete();
                }
            }
            
            //没有检测到同名模板，则向报表数据集中增加一个新行            
                DataRow newRow = ReportTable.NewRow();
                ReportTable.Rows.Add(newRow);
            

            using (MemoryStream stream = new MemoryStream())
            {
                report.Save(stream);

                //写入xml配置文件
                newRow["ReportName"] = reportName;
                newRow["ReportSql"] = "";
                newRow["ReportLastTime"]=DateTime.Now.ToString();
                newRow["ReportStream"] = stream.ToArray();
            }
            WriteRptTemplate();
        }

        private DataSet GetDs(string StringSql="")
        {
            DataSet ds = new DataSet();
            DataSet retds = new DataSet("mydata");//实例化一个名字叫 mydata 非类型化数据集
            string sql = "select "
    + " a.djbh,a.rq,a.ontime,a.thfs,a.fhdj,a.bianh,a.bm,a.ywy,a.username,a.jhw,a.fuhr,a.kpman ,"
    +" replace(replace(a.beizhu,'WMS作业完成',''),'WMS作业中','') as beizhu,a.webdjbh,a.xsjsfs, "
    +" c.danwbh,c.dwmch,c.lxr,c.ckdz,d.gzdh,a.je,sum(b.hsje) as hsje,sum(baozhshl) as baozhshl,count(spid) as count,a.fhtbh "
    +" from pf_ckhz a(nolock) "
    +" left join zhiydoc  d(nolock) on a.ywyid=d.dzyid "
    +" ,pf_ckmx b(nolock),mchk c(nolock) "
    +" where a.djbh=b.djbh and a.dwbh=c.dwbh  "
    //+" and isnull(b.is_dayin,'否')<>'是' " 
    +" and djbs='XSA' "
    +" and a.rq>=convert(varchar(10),getdate()-10,120) "
    +" and a.djbh='XSAZDA00614650' "
    + " group by a.djbh,a.rq,a.ontime,a.thfs,a.fhdj,a.bianh,a.bm,a.ywy,a.username,a.jhw,a.fuhr,a.kpman ,a.beizhu,a.webdjbh,a.xsjsfs, "
    +" c.danwbh,c.dwmch,c.lxr,c.ckdz,d.gzdh,a.je ,a.jhw,a.beizhu,a.fhtbh "
    + " order by a.djbh;"
    +" select sum(a.je) as je,b.qxscxkzh,b.spbh,b.spmch,b.shpgg,b.dw,b.shengccj,b.shpchd,b.pizhwh,b.jixing,b.sclx, "
    +" a.pihao,a.baozhiqi,a.sxrq,sum(a.shl) as shl,a.hshj,sum(a.hsje) as hsje,b.lshj,b.gawj,b.is_jy, "
    +" sum(a.baozhshl) as baozhshl,b.wtscdw,c.huowname, "
    +" (select sum(baozhshl) from pf_ckmx(nolock) where djbh=a.djbh) as jiansh, "
    +" (select sum(hsje) from pf_ckmx(nolock) where djbh=a.djbh) as hsjehj, "
    +" (select top 1 '移' from dbmx(nolock) where ydjbh=a.djbh and spid=b.spid) as isyk "
    +" from pf_ckmx a(nolock),spkfk b(nolock),huoweizl c(nolock) "
    +" where a.hw=c.hw and a.spid=b.spid "
    +" and a.djbh='XSAZDA00614650' "
    +" group by b.qxscxkzh,b.spbh,b.spmch,b.shpgg,b.dw,b.shengccj,b.shpchd,b.pizhwh,b.jixing, "
    +" b.sclx,a.pihao,a.baozhiqi,a.sxrq,a.hshj,b.lshj,b.gawj,b.is_jy,b.wtscdw,c.huowname,a.djbh,b.spid,c.hwbh,a.jwh "
    +" order by c.hwbh,a.jwh,b.spbh,a.pihao";
            /*
           DataTable HZ = new DataTable("汇总");//new一个名字叫master（主表名）的数据表
            HZ = mssql.ExecuteDt("select b.dwbh,b.danwbh,b.dwmch,b.lxr,b.dzdh,a.* from ksoa.dbo.pf_ckhz a,ksoa.dbo.mchk b where a.dwbh=b.dwbh and a.djbh='XSAZDA00575013' ");
            HZ.TableName = "汇总";
            DataTable MX = new DataTable("明细");//new一个名字叫cong（从表名）的数据表

            ds.Tables.Add(init.DataView(HZ));//把数据表添加到数据集中
            MX = mssql.ExecuteDt("select b.spid,b.spbh,b.spmch,b.shpgg,b.dw,b.shengccj,b.jixing,b.pizhwh,a.*,c.hwbh,c.huowname from ksoa.dbo.pf_ckmx a,ksoa.dbo.spkfk b,ksoa.dbo.huoweizl c where a.spid=b.spid and a.hw=c.hw and a.djbh='XSAZDA00575013' ");
            MX.TableName = "明细";
            ds.Tables.Add(init.DataView(MX));//同上
            */
            try
            {
                StringSql = string.IsNullOrEmpty(StringSql) ? sql : StringSql;

                ds = mssql.ExecuteDs(StringSql);
                foreach (DataTable dt in ds.Tables)
                {
                    //dt.TableName = "";
                    DataTable newdt = init.DataView(dt.Copy());
                    retds.Tables.Add(newdt);//同上
                }
            }catch(Exception ex)
            {
                init.WriteLog(ex.ToString(),true);
            }
            return retds;
        }
    }
}

